package com.winexpress.account;

import com.winexpress.util.GoogleAnalytics;
import com.winexpress.util.Log;
import com.winexpress.util.SessionAttributes;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceRef;

@WebServlet(name = "UserLogin", urlPatterns = {"/login/*"})
public class UserLogin extends HttpServlet {

    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/WineXpress-war/LoginWS.wsdl")
    private LoginWS_Service service;
    
    GoogleAnalytics googleService = new GoogleAnalytics();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        RequestDispatcher dispatcher;
        ServletContext servletContext = getServletContext();
        String page = request.getPathInfo();
        page = page.substring(1);
        HttpSession session = request.getSession();
        String id = null;

        //Get Number of Items in Cart
        int count = 0;

        if (session.getAttribute("items") == null) {
            int i = 0;
            request.setAttribute("itemsnum", i);
        } else {
            String items = (String) session.getAttribute("items");
            String[] array = items.split("\\;");
            for (int i = 1; i < array.length; i = i + 2) {
                count = count + Integer.parseInt(array[i]);
            }
            request.setAttribute("itemsnum", count);
        }
        //End Number of Items in Cart

        if (page.equals("adminHome")) {
            id = loginAdmin(request);
            session.setAttribute(SessionAttributes.IS_ADMIN, true);
        } else {
            id = loginCustomer(request);
            session.setAttribute(SessionAttributes.IS_ADMIN, false);
        }
        if (id != null) {
            session.setAttribute(SessionAttributes.USER_ID, id);
            if (page.equals("adminHome")) {
                Admin admin = getAdminById(new Long(id));
                session.setAttribute(SessionAttributes.USER_FIRST_NAME, admin.getFirstName());
                session.setAttribute(SessionAttributes.USER_LAST_NAME, admin.getLastName());
                session.setAttribute(SessionAttributes.USER_EMAIL, admin.getEmail());
                session.setAttribute(SessionAttributes.USER_PHONE_NUMBER, admin.getPhoneNumber());
                session.setAttribute(SessionAttributes.USER_AGE, admin.getAge());
                
                //UserLogin.java GoogleAnalytics
                if (session.getAttribute("totalPageViews") == null){
                    googleService.runGoogleAnalytics();

                    session.setAttribute("totalPageViews",googleService.getTotalPageViews());
                    session.setAttribute("totalVisits", googleService.getTotalVisits());
                    session.setAttribute("totalNewVisits", googleService.getTotalNewVisits());
                    session.setAttribute("uniqueVisitos", googleService.getUniqueVisitors());
                    session.setAttribute("avgVisitDuration_hour", googleService.getAvgVisitDuration_hour());
                    session.setAttribute("avgVisitDuration_min", googleService.getAvgVisitDuration_min());
                    session.setAttribute("avgVisitDuration_sec", googleService.getAvgVisitDuration_sec());
                    session.setAttribute("bounceRate", googleService.getBounceRate());
                    session.setAttribute("percentNewVisits", googleService.getPercentNewVisits());
                    session.setAttribute("pagesPerVisit", googleService.getPagesPerVisit());

                    List<String> days = (List<String>) googleService.getDays();
                    List<String> pageViewsByDay = (List<String>) googleService.getPageViewsByDay();
                    List<String> visitsByDay = (List<String>) googleService.getVisitsByDay();
                    List<String> newVisitsByDay = (List<String>) googleService.getNewVisitsByDay();

                    int j = 7;
                    int lastDay=new Integer(days.get(days.size()-1)).intValue();
                    int index = days.size()-1;
                    for (int i=days.size();i>0;i--){
                        session.setAttribute("day"+j,lastDay);
                        session.setAttribute("pageViewsDay"+j, pageViewsByDay.get(index));
                        session.setAttribute("visitsDay"+j, visitsByDay.get(index));
                        session.setAttribute("newVisitsDay"+j, newVisitsByDay.get(index));

                        j--;
                        index--;
                        lastDay--;
                    }

                    for (int i=j;i>0;i--){
                        session.setAttribute("day"+j,lastDay);
                        session.setAttribute("pageViewsDay"+j, 0);
                        session.setAttribute("visitsDay"+j, 0);
                        session.setAttribute("newVisitsDay"+j, 0);
                        j--;
                        lastDay--;
                    }
                }
                
                Log.info("adminID = " + id + " Log in");
            } else {
                Customer customer = getCustomerById(new Long(id));
                session.setAttribute(SessionAttributes.USER_FIRST_NAME, customer.getFirstName());
                session.setAttribute(SessionAttributes.USER_LAST_NAME, customer.getLastName());
                session.setAttribute(SessionAttributes.USER_EMAIL, customer.getEmail());
                session.setAttribute(SessionAttributes.USER_PHONE_NUMBER, customer.getPhoneNumber());
                session.setAttribute(SessionAttributes.USER_AGE, customer.getAge());
                session.setAttribute(SessionAttributes.CUSTOMER_ADDRESS, customer.getAddress());
                session.setAttribute(SessionAttributes.CUSTOMER_CREDIT_CARD_NUMBER, customer.getCreditCardNumber());
//                    session.setAttribute("items", "");
                Log.info("customerID = " + id + " Log in");
            }
        } else {
            response.sendRedirect("/WineXpressClient/loginFail.jsp");
            return;
        }
        dispatcher = servletContext.getNamedDispatcher(page);
        if (dispatcher == null) {
            dispatcher = servletContext.getNamedDispatcher("Error");
        }
        dispatcher.forward(request, response);

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }

    private String loginCustomer(HttpServletRequest request) {
        LoginWS port = service.getLoginWSPort();
        String email = request.getParameter("inputEmail");
        String password = request.getParameter("inputPassword");
        String result = null;
        try {
            Customer customer = new Customer();
            customer.setEmail(email);
            customer.setPassword(password);
            result = port.login(customer);
        } catch (Exception_Exception ex) {
            Logger.getLogger(UserLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;

    }

    private String loginAdmin(HttpServletRequest request) {
        LoginWS port = service.getLoginWSPort();
        String email = request.getParameter("inputEmail");
        String password = request.getParameter("inputPassword");
        String result = null;
        try {
            User admin = new User();
            admin.setEmail(email);
            admin.setPassword(password);
            result = port.loginAdmin(admin);
        } catch (Exception_Exception ex) {
            Logger.getLogger(UserLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    private Customer getCustomerById(java.lang.Long id) {
        com.winexpress.account.LoginWS port = service.getLoginWSPort();
        return port.getCustomerById(id);
    }

    private Admin getAdminById(java.lang.Long id) {
        com.winexpress.account.LoginWS port = service.getLoginWSPort();
        return port.getAdminById(id);
    }

}
